package com.cheyunkeji.er.activity;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
//import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.adapter.fastevaluate.FastEvaluateChannelListAdapter;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.ChannelCategory;
import com.cheyunkeji.er.bean.UnAvailableChannelBean;
import com.cheyunkeji.er.bean.UserInfo;
import com.cheyunkeji.er.bean.evaluate.CarTempAttrList;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.utils.SerializeUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;

public class ChannelSelectActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private static final String TAG = ChannelSelectActivity.class.getSimpleName();

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.btn_join)
    Button btnJoin;
    @BindView(R.id.ll_unaccessible_page)
    LinearLayout llUnaccessiblePage;
    @BindView(R.id.activity_fast_evaluate)
    LinearLayout activityFastEvaluate;
    @BindView(R.id.lv_channel_list)
    ListView lvChannelList;
    @BindView(R.id.ll_channel_company)
    RelativeLayout llChannelCompany;
//    @BindView(R.id.tv_create_new_organization)
////    TextView tvCreateOrganization;
    @BindView(R.id.btn_add_organize)
    Button btn_add_organize;

    private long mExitTime = 0;

    private LinearLayout footerView;

    private FastEvaluateChannelListAdapter listAdapter;

    private List<UserInfo.ChannelListBean> channelList;
    private List<UnAvailableChannelBean> unAvailableChannelBeanList;

    private Button btnAddNewOrganize;

    @Override
    protected void init() {

        setContentView(R.layout.er_activity_channel_select);
        ButterKnife.bind(this);

//        if(!MyApplication.getInstance().hasCheckVersion) {
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    UpdatePresenter presenter = new UpdatePresenter(ChannelSelectActivity.this, 3);
//                    presenter.getVersionInfo();
//                    MyApplication.getInstance().hasCheckVersion = true;
//                }
//            }, 1000);
//        }
    }

    /**
     * 初始化通道列表，如果列表为空则显示
     */
    private void initChannelList() {
        channelList = ChannelInfoUtil.getChannelInfoList();
        unAvailableChannelBeanList = ChannelInfoUtil.getUnavailableChannelList();

//      通道数量为空时，显示空白界面
        if ((channelList == null && unAvailableChannelBeanList == null) || (channelList.size() == 0 && unAvailableChannelBeanList.size() == 0)) {
            llChannelCompany.setVisibility(View.INVISIBLE);
            btnJoin.setOnClickListener(this);
//            tvCreateOrganization.setOnClickListener(this);
//            tvCreateOrganization.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//            tvCreateOrganization.getPaint().setAntiAlias(true);
            SToast.show("当前账号无通道");
//            MyApplication.phone = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
//            UserInfoManager.getInstance(MyApplication.getInstance()).clear();
//            MyApplication.logout(MyApplication.getInstance());
        } else {

            listAdapter = new FastEvaluateChannelListAdapter((ArrayList<UserInfo.ChannelListBean>) channelList, (ArrayList<UnAvailableChannelBean>) unAvailableChannelBeanList, this);
            lvChannelList.setAdapter(listAdapter);
            lvChannelList.setOnItemClickListener(this);
            for (UserInfo.ChannelListBean channelListBean : channelList) {
                Log.e(TAG, "initChannelList:通道列表 ID : " + channelListBean.getChannel());
            }

        }


    }


//    @Override
//    public void onBackPressed() {
//
//        if ((System.currentTimeMillis() - mExitTime) > 2000) {
//            ToastUtil.showToast("再按一次退出程序");
//            mExitTime = System.currentTimeMillis();
//        } else {
//            MyApplication.getInstance().exit();
//        }
//    }

    /**
     * 缓存临时信息列表数据(getTempAttrList接口)
     */
    private void cacheCarTempInfo() {

        HashMap<String, String> params = new HashMap<>();
        params.put("field", HttpConstants.TEMP_ATTR_LIST_REQUEST_FILED);
        ApiClient.postForm(HttpConstants.CAR_TEMP_ATTR_LIST, params, new RespCallback<CarTempAttrList>() {

            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
                llChannelCompany.setVisibility(View.INVISIBLE);
                btnJoin.setOnClickListener(ChannelSelectActivity.this);
//                tvCreateOrganization.setOnClickListener(ChannelSelectActivity.this);
//                tvCreateOrganization.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//                tvCreateOrganization.getPaint().setAntiAlias(true);
            }

            @Override
            protected void onSuccess(CarTempAttrList data) {

                if (null != data) {
                    SerializeUtil.saveCarTempAttrList(data);
                    MyApplication.getInstance().setAttrList(data);
                }
            }


        });

    }


//    /**
//     * 缓存基础信息列表所有对应字段名称(getAttrList接口)
//     */
//    private void cacheBasicInfoList() {
//
//        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
//        params.put("field", HttpConstants.BASIC_INFO_LIST);
//
//        ApiClient.postForm(HttpConstants.GET_CAR_BASIC_INFO_LIST, params, new RespCallback<CarBasicInfoList>() {
//
//            @Override
//            protected void onRequestFailed(String msg) {
//                SToast.show(msg);
//            }
//
//            @Override
//            protected void onSuccess(CarBasicInfoList data) {
//
//                if (null != data) {
//                    SerializeUtil.saveCarBasicInfoList(data);
//                    MyApplication.setBasicList(data);
//
//                }
//            }
//
////            @Override
////            public void onAfter(int id) {
////                dismissDialog();
////            }
////
////            @Override
////            public void onBefore(Request request, int id) {
////                showDialog();
////            }
//        });
//
//    }


    @Override
    protected void initView() {

        vTopbar.setTitle("门店选择");
//        vTopbar.setLeft("", R.mipmap.er_ic_back, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                MyApplication.pwd = UserInfoManager.getInstance(MyApplication.getInstance()).getPwd();
//                MyApplication.phone = UserInfoManager.getInstance(MyApplication.getInstance()).getMobile();
//                UserInfoManager.getInstance(MyApplication.getInstance()).clear();
//                MyApplication.logout(MyApplication.getInstance());
//            }
//        });
        btnJoin.setOnClickListener(this);
        btn_add_organize.setOnClickListener(this);
//        vTopbar.setRight("创建", -1, this);

    }

    @Override
    protected void initData() {
        UserInfo.ChannelListBean currentChannelInfo = ChannelInfoUtil.getCurrentChannelInfo();
        if (currentChannelInfo!=null){
            UserInfoManager.getInstance(MyApplication.getInstance()).saveY7e_ckey(currentChannelInfo.getY7e_ckey());
            startActivity(new Intent(ChannelSelectActivity.this, ModuleSelectActivity.class));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadChannelList();
    }

    private void loadChannelList() {

        HashMap<String, String> params = new HashMap<>();
        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
        ApiClient.postForm(HttpConstants.GET_MY_CHANNEL_LIST, params, new RespCallback<ChannelCategory>() {

            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onSuccess(ChannelCategory data) {

                Log.e(TAG, "onSuccess: " + data.getNo_list().size() + "\t " + data.getOk_list().size());

                saveChannelInfo(data.getOk_list(), data.getNo_list());
                initChannelList();

            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }

        });
    }


    private void saveChannelInfo(List<UserInfo.ChannelListBean> availableChannelList, List<UnAvailableChannelBean> unAvailableChannelList) {

        if (availableChannelList != null) {
            ChannelInfoUtil.saveChannelInfoList(availableChannelList);
        }

        if (null != unAvailableChannelList) {
            ChannelInfoUtil.saveUnavailableChannelList(unAvailableChannelList);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

//            case R.id.tv_create_new_organization:
//            case R.id.vRight:
//                startActivity(new Intent(this, CreateNewOrganizeActivity.class));
//                break;

            case R.id.btn_join:
            case R.id.btn_add_organize:
                startActivity(new Intent(this, JoinNewOrganizeActivity.class));
                break;

            default:
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (parent.getItemAtPosition(position) instanceof UnAvailableChannelBean) {
            SToast.show("当前通道不可用");
            return;
        }

        UserInfo.ChannelListBean bean = channelList.get(position);

        if ((System.currentTimeMillis() / 1000 - bean.getEndtime()) > 0) {
            SToast.show(getString(R.string.channel_outof_date));
            return;
        }
        if (bean.getLocked() == 1) {
            SToast.show(getString(R.string.channel_locked));
            return;
        }

        if (bean.getState() == 0) {
            SToast.show("通道申请使用中");
            return;
        }
        if (bean.getState() == 3) {
            SToast.show("通道申请已驳回");
            return;
        }
        if (bean.getState() == 4) {
            SToast.show("通道申请已撤销");
            return;
        }
        if (bean.getState() == 1 || bean.getState() == 2) {
            if (bean.getCm_state() == 0) {
                SToast.show("通道用户申请使用中");
                return;
            }
            if (bean.getCm_state() == 3) {
                SToast.show("通道用户申请已驳回");
                return;
            }
            if (bean.getCm_state() == 4) {
                SToast.show("通道用户已锁定");
                return;
            }
            if (bean.getCm_state() == 5) {
                SToast.show("撤销绑定/申请/邀请");
                return;
            }
        }
        //清空默认选择的模块
//        MyApplication.setCurrentModuleType(0);
        startActivity(new Intent(ChannelSelectActivity.this, ModuleSelectActivity.class));

        ChannelInfoUtil.saveCurrentChannelInfo(channelList.get(position));

//        UserInfoManager.getInstance(MyApplication.getInstance().getApplicationContext()).saveCKey(channelList.get(position).getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
//         UserInfoManager.getInstance(MyApplication.getInstance().getApplicationContext()).saveCKey(channelList.get(position).getY7e_ckey());
        UserInfoManager.getInstance(MyApplication.getInstance()).saveY7e_ckey(channelList.get(position).getY7e_ckey());

        cacheCarTempInfo();

    }


}
